package com.studyjun.filmsimple;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import android.app.Activity;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class ShortVideoActivity extends Activity implements
		SurfaceHolder.Callback {

	@Override
	protected void onDestroy() {
		stopRecording();
		super.onDestroy();
	}

	private SurfaceHolder surfaceHolder;
	private SurfaceView surfaceView;
	public MediaRecorder mrec = new MediaRecorder();
	private Camera mCamera;
	private Button recording;
	private Progress progress;
	private RelativeLayout fLayout;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_short_video);

		surfaceView = (SurfaceView) findViewById(R.id.short_video_surface);
		recording = (Button) findViewById(R.id.short_video_button);
		progress = (Progress) findViewById(R.id.short_video_progress);

		mCamera = Camera.open();

		Parameters params = mCamera.getParameters();
		params.setRotation(90);


		params.setPreviewSize(226, 160);
		mCamera.setParameters(params);
		mCamera.setDisplayOrientation(90);

		surfaceHolder = surfaceView.getHolder();
		surfaceHolder.addCallback(this);
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		pressRec();
		
		surfaceView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
//					new CaptureRect(ShortVideoActivity.this,event.getRawX(),event.getRawY(),200,200,Color.GREEN);
					mCamera.autoFocus(new AutoFocusCallback() {
						
						@Override
						public void onAutoFocus(boolean success, Camera camera) {
							if (success) {
								Toast.makeText(getApplicationContext(), "success", 500).show();
							} else{
								Toast.makeText(getApplicationContext(), "failure", 500).show();
							}
						}
					});
					break;

				default:
					break;
				}
				return true;
			}
		});

	}

	
	
	/**
	 * 按住拍
	 */
	public void pressRec() {
		recording.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN: // 按下拍摄
					try {
						startRecording();
					} catch (Exception e) {
						String message = e.getMessage();
						Log.i(null, "Problem " + message);
						mrec.release();
					}
					progress.start(true);
					break;
				case MotionEvent.ACTION_UP:// 松手保存
					stopRecording();
					progress.start(false);
					break;
				case MotionEvent.ACTION_MOVE: //移动
					float y = event.getY();
					if (y<0) { //小于0时是移出按钮
						progress.cancel(true);
					} else{
						progress.cancel(false);
					}
				default:
					break;
				}
				return false;
			}
		});
	}

	protected void startRecording() throws IOException {
		if (mCamera == null)
			mCamera = Camera.open();

		Parameters params = mCamera.getParameters();
		


		params.setPreviewSize(160, 226);
		mCamera.setParameters(params);
		
		String filename;
		String path;

		path = Environment.getExternalStorageDirectory().getAbsolutePath()
				.toString();

		Date date = new Date();
		filename = "/rec" + date.toString().replace(" ", "_").replace(":", "_")
				+ ".mp4";

		// create empty file it must use
		File file = new File(path, filename);

		mrec = new MediaRecorder();

		mCamera.lock();
		mCamera.unlock();


		// If you change sequence it will not work.
		mrec.setCamera(mCamera);
		mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
		mrec.setAudioSource(MediaRecorder.AudioSource.MIC);
		mrec.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
		mrec.setVideoEncoder(MediaRecorder.VideoEncoder.MPEG_4_SP);
		mrec.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		mrec.setPreviewDisplay(surfaceHolder.getSurface());
		mrec.setOutputFile(path + filename);
		mrec.setOrientationHint(0);
		mrec.setVideoSize(160, 226);
		mrec.prepare();
		mrec.start();

	}

	protected void stopRecording() {

		if (mrec != null) {
			mrec.stop();
			mrec.release();
			mrec = null;
		}
	}

	private void releaseMediaRecorder() {

		if (mrec != null) {
			mrec.reset(); // clear recorder configuration
			mrec.release(); // release the recorder object
		}
	}

	private void releaseCamera() {
		if (mCamera != null) {
			mCamera.release(); // release the camera for other applications
			mCamera = null;
		}

	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {

		if (mCamera != null) {
			Parameters params = mCamera.getParameters();
			params.setPreviewSize(226, 160);
			mCamera.setParameters(params);
			Log.i("Surface", "Created");
		} else {
			Toast.makeText(getApplicationContext(), "Camera not available!",
					Toast.LENGTH_LONG).show();

			finish();
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		mCamera.stopPreview();
		mCamera.release();

	}
}
